package com.logic.meeting.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.logic.meeting.app.R;
import com.logic.meeting.app.R2;
import com.logic.meeting.app.entity.MeetingHomeListEntity;
import com.logic.meeting.app.entity.VersionEntity;
import com.logic.meeting.app.fusion.FusionCode;
import com.logic.meeting.app.fusion.FusionPre;
import com.logic.meeting.app.util.ApkManager;
import com.logic.meeting.app.util.ClickUtil;
import com.logic.meeting.app.util.DialogUtil;
import com.logic.meeting.app.util.DownloadUtil;
import com.logic.meeting.core.delegates.AtmosDelegate;
import com.logic.meeting.core.net.HttpHelper;
import com.logic.meeting.core.net.HttpUrl;
import com.logic.meeting.core.net.callback.IError;
import com.logic.meeting.core.net.callback.IFailure;
import com.logic.meeting.core.net.callback.ISuccess;
import com.logic.meeting.core.util.StringUtil;
import com.logic.meeting.core.util.dimen.DimenUtil;
import com.logic.meeting.core.util.storage.AtmosPreference;

import java.lang.reflect.Type;

import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class IndexSettingPageDelegate extends AtmosDelegate {

    @OnClick(R2.id.tv_restart_machine)
    void onRestart() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.reboot");
        getProxyActivity().sendBroadcast(intent);
    }

    @OnClick(R2.id.tv_close_app)
    void onClose() {
        getProxyActivity().finish();
    }

    @OnClick(R2.id.tv_get_new_version)
    void onGetNewVersion() {
        getVersion();
    }

    @OnClick(R2.id.tv_back)
    void onBack() {
        getSupportDelegate().pop();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_setting_page;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

    }

    private void getVersion() {

        HttpHelper.RestClientGet(HttpUrl.GET_NEW_VERSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        Type type = new TypeToken<VersionEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        VersionEntity mData = gson.fromJson(response, type);
                        if (mData.getStatus().equals(FusionCode.SUCCESS)) {
                            if (mData.getData().getContent().get(0).getValue().equals(ApkManager.getVersionName(getContext()))) {
                                DialogUtil.showCardErrorDialog(getContext(), "已是最新版本", "确定");
                            } else {
                                showTipsDialog(mData);
                            }
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    @SuppressLint("SetTextI18n")
    public void showTipsDialog(VersionEntity versionData) {
        final Dialog serviceDialog = new Dialog(getContext(), R.style.dialog);
        serviceDialog.setCancelable(false);
        Window window = serviceDialog.getWindow();
        window.setContentView(R.layout.dialog_download_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.6);
        int height = (int) (DimenUtil.getScreenHeight() * 0.6);
        window.setLayout(width, height);

        AppCompatTextView tvApkInfo = window.findViewById(R.id.tv_apk_info);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);

        tvApkInfo.setText("当前设备版本为：v" + ApkManager.getVersionName(getContext()) + "\n当前线上最新版本为：v" + versionData.getData().getContent().get(0).getValue());

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceDialog.dismiss();
                downloadFile(versionData.getData().getContent().get(1).getValue(), String.valueOf(System.currentTimeMillis()));

            }
        });
        serviceDialog.show();
    }


    private void downloadFile(String downLoadUrl, String version) {
        IndexSettingPageDelegatePermissionsDispatcher.startCheckUpdateWithCheck(IndexSettingPageDelegate.this, downLoadUrl, version);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_BOOT_COMPLETED})
    void startCheckUpdate(String url, String version) {
        DownloadUtil.DownLoadFile(getContext(), url, version + "-" + System.currentTimeMillis());
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_BOOT_COMPLETED})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        IndexSettingPageDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}
